'use strict';
const wx = require("wx-common")
const {
  Base64
} = require("base64")
exports.main = async (event, context) => {
  //event为客户端上传的参数
  console.log('event : ', event)
  const db = uniCloud.database()
  const {
    code
  } = event
  const res = await uniCloud.httpclient.request(
    `https://api.weixin.qq.com/sns/jscode2session?appid=${wx.appid}&secret=${wx.appSecret}&js_code=${code}&grant_type=authorization_code`, {
      dataType: "json"
    }
  )
  const openid = res.data.openid
  const isOpenid = await db.collection("users").where({
    openid: openid
  }).get()
  let myopenid = ''
  let base = new Base64()
  let newopenid = base.encode(openid)
  if (isOpenid.data.length > 0) {
    // console.log(isOpenid, openid);
    myopenid = newopenid
  } else {
    let userData = {
      openid: openid,
      nickName: '',
      avatarUrl: '',
      collection: []
    }
    await db.collection("users").add(userData)
    myopenid = newopenid
  }
  // console.log(res);
  //返回数据给客户端
  return myopenid
};
